use musicman
go 

IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE SPECIFIC_SCHEMA = 'dbo' AND SPECIFIC_NAME = 'fn_get_admin_adresses' AND ROUTINE_TYPE='FUNCTION')
DROP FUNCTION [dbo].[fn_get_admin_adresses]
GO

CREATE function [dbo].[fn_get_admin_adresses]() returns varchar(2048)
as 
begin
	declare @addresses varchar(2048)
	declare @address varchar(50)
	DECLARE @cur CURSOR

	SET @addresses = '';
	SET @cur = CURSOR FOR
	select u.emailaddress from musicman.dbo.users u join musicman.dbo.userRoles r on u.personid = r.userid where r.role = 'ADMIN'

	OPEN @cur
	FETCH NEXT FROM @cur INTO @address

	WHILE @@FETCH_STATUS = 0
	BEGIN
		set @addresses = @addresses + @address + ';'
		FETCH NEXT FROM @cur INTO @address
	END

	CLOSE @cur
	DEALLOCATE @cur
	
	RETURN @addresses
END
GO 